#include "..\include\o_graphic_dx9.h"
 
Graphic::Graphic()
{}

Graphic::~Graphic()
{}

void Graphic::release()
{
     graphic_cfg.p_device->Release();
     graphic_cfg.p_object->Release();
}

bool Graphic::init_graphic(const Core_Config &core_cfg)
{
    graphic_cfg.p_object=Direct3DCreate9(D3D_SDK_VERSION);

    if(graphic_cfg.p_object == NULL)
    {
        return false;
    }

    graphic_cfg.p_object->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &graphic_cfg.display_mode );
    graphic_cfg.p_object->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &graphic_cfg.caps );

    ZeroMemory(&graphic_cfg.pp,sizeof(D3DPRESENT_PARAMETERS));

    graphic_cfg.pp.BackBufferWidth            = (!core_cfg.b_fullscreen) ? 0 : graphic_cfg.display_mode.Width;
    graphic_cfg.pp.BackBufferHeight           = (!core_cfg.b_fullscreen) ? 0 : graphic_cfg.display_mode.Height;
	graphic_cfg.pp.BackBufferFormat           = graphic_cfg.display_mode.Format;
    graphic_cfg.pp.BackBufferCount            = 1;
    graphic_cfg.pp.EnableAutoDepthStencil     = FALSE;
    graphic_cfg.pp.MultiSampleType            = D3DMULTISAMPLE_4_SAMPLES;
    graphic_cfg.pp.MultiSampleQuality         = 0;
    graphic_cfg.pp.SwapEffect                 = D3DSWAPEFFECT_DISCARD;
    graphic_cfg.pp.hDeviceWindow              = core_cfg.h_wnd;
    graphic_cfg.pp.Windowed                   = !core_cfg.b_fullscreen;
	graphic_cfg.pp.FullScreen_RefreshRateInHz = (!core_cfg.b_fullscreen) ? 0 : graphic_cfg.display_mode.RefreshRate;
    graphic_cfg.pp.PresentationInterval       = D3DPRESENT_INTERVAL_IMMEDIATE;

    DWORD vertex_flag = 0;
    if ( graphic_cfg.caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT )
    {
        vertex_flag = D3DCREATE_HARDWARE_VERTEXPROCESSING;
		if ( graphic_cfg.caps.DevCaps & D3DDEVCAPS_PUREDEVICE )
		{
			vertex_flag |= D3DCREATE_PUREDEVICE;
		}
	}
    else
    {
        vertex_flag = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
	}

    if(FAILED(graphic_cfg.p_object->CreateDevice(
                    D3DADAPTER_DEFAULT,
                    D3DDEVTYPE_HAL,
                    core_cfg.h_wnd,
                    vertex_flag,
                    &graphic_cfg.pp,
                    &graphic_cfg.p_device )))
    {
        return false;
    }

    return true;
}

void Graphic::reset_graphic(const Core_Config &cfg)
{
    graphic_cfg.p_device->Release();
    init_graphic(cfg);
}

void Graphic::begin_render()
{
    HRESULT hr = graphic_cfg.p_device->TestCooperativeLevel();
    if(hr == D3DERR_DEVICENOTRESET)
    {
        graphic_cfg.p_device->Reset(&graphic_cfg.pp);
    }

    graphic_cfg.p_device->Clear(NULL,NULL,graphic_cfg.dw_clear_buffer,graphic_cfg.dw_clear_color,1.0f,NULL);
    graphic_cfg.p_device->BeginScene();
}

void Graphic::end_render()
{
    graphic_cfg.p_device->EndScene();
    graphic_cfg.p_device->Present(NULL,NULL,NULL,NULL);
}
